package com.redoor.app.stake.basicdata.aop;

import com.alibaba.druid.support.json.JSONUtils;
import com.redoor.app.stake.common.utils.JsonUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Service层调用日志记录
 * Created by wangjunlei on 2018/3/4.
 */
@Aspect
@Component
public class ServiceLogAspect {
    protected static org.slf4j.Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);

    private Map logMap;

    @Pointcut("execution(!@com.redoor.app.stake.basicdata.aop.IgnoreAopLog * com.redoor.app.stake.basicdata.service.impl.*.*(..))")
    public void ServiceLog() {

    }

    @Before("ServiceLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        logMap = new HashMap();
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(attributes != null){
            HttpServletRequest request = attributes.getRequest();
            logMap.put("URL",request.getRequestURL().toString());
            logMap.put("HTTP_METHOD",request.getMethod());
            logMap.put("IP",request.getRemoteAddr());
        }
        logMap.put("CLASS_METHOD",joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        logMap.put("ARGS",Arrays.toString(joinPoint.getArgs()));
        logMap.put("START_TIME",System.currentTimeMillis());
    }

    @AfterReturning(returning = "ret", pointcut = "ServiceLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        if(ret instanceof Collection){
            logger.info("RESPONSE LIST SIZE: " + ((Collection) ret).size());
            if(null != ret && ((Collection) ret).size() > 0){
                logMap.put("RESPONSE",((Collection) ret).iterator().next());
            } else {
                logMap.put("RESPONSE","empty");
            }
        } else if(ret instanceof Map){
            logger.info("RESPONSE MAP SIZE: " + ((Map) ret).size());
            if(null != ret && ((Map) ret).size() > 0){
                logMap.put("RESPONSE",((Map) ret).keySet().iterator().next());
            } else {
                logMap.put("RESPONSE","empty");
            }
        } else {
            logger.debug("RESPONSE : " + ret);
            logMap.put("RESPONSE",ret);
        }
        // 处理完请求，返回内容
        logMap.put("END_TIME",System.currentTimeMillis());
        try {
            // 记录下请求内容
            logger.info("services info : " + JsonUtils.toJson(logMap));
        } catch (Exception ex) {

        }

    }

    @AfterThrowing(throwing="ex", pointcut = "ServiceLog()")
    public void doAferThrowing(Throwable ex){
        logMap.put("END_TIME",System.currentTimeMillis());
        logMap.put("RESPONSE",ex.getLocalizedMessage());
        // 记录下请求内容
        try {
            // 记录下请求内容
            logger.info("services info : " + JsonUtils.toJson(logMap));
        } catch (Exception ex1) {

        }
    }
}
